//
//  BLESetWifiInputController.m
//  RuiHeApp
//
//  Created by Jun on 2023/10/11.
//

#import "BLESetWifiInputController.h"
#import "RHChoiceWiFiView.h"
#import "CBLEDataMnger.h"
#import "CBLECenterMnger.h"
#import "CBLEDataParse.h"
#import "RHBleCmdManager.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <NetworkExtension/NetworkExtension.h>
#import "BLEWiFiConnectingVC.h"
#import "RHLocalSettingTypeModel.h"
#import "CDZQRScanViewController.h"
#import "RHNavigationController.h"
#import "NetworkConfig.h"

@interface BLESetWifiInputController ()

@property (nonatomic ,strong) QMUILabel *nameLab;

@property (nonatomic ,strong) QMUILabel *macLab;

@property (nonatomic ,strong) QMUITextField *ssidInputV;

@property (nonatomic ,strong) QMUITextField *passwordInputV;

@property (nonatomic ,strong) CDataPheralInfo *pheralInfo;

@property (nonatomic ,strong) UIImageView *stepImg;

@property (nonatomic ,strong) QMUIButton *remeberBtn;

@property (nonatomic ,strong) QMUITextField *secretTextField;

@property (nonatomic ,copy) NSString *deviceId;//如果点击的是自己名下的设备,传设备id过去获取设备秘钥
@end

@implementation BLESetWifiInputController


- (instancetype)initWithPheralInfo:(CDataPheralInfo *)pheralInfo{
    self = [super init];
    
    if(self){
        self.pheralInfo = pheralInfo;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"蓝牙配网".rh_localized;
    [self setupUI];
    [self createCmd];
    [self checkDeviceId];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(void)createCmd
{
    //WIFI名称和密码 设备密钥  区域 品牌 结束命令
    NSMutableArray *cmdArr = [NSMutableArray array];
    
    //有主控的时间校准指令  直接写3个寄存器,和参数设置里的时间校准一样   (考虑设备旧固件指令没有回复或者master或者失联的情况,时间校准先去掉)
//    if ([CBLECenterMnger shareMnger].curPheral.hasMaster) {
//        NSArray *masterCmdArr = @[@{
//            @"field":@"Pck_ctrlTimyear",
//            @"regAddr":@(6002),
//            @"bitWidth":@(16),
//            @"type":@"date",
//            @"cmdType":@(LocalSettingType_Master)
//        }];
//        
//        if ([CBLECenterMnger shareMnger].curPheral.wifiType == DevWiFiType362K) {
//            [cmdArr addObjectsFromArray:masterCmdArr];
//        }
//        
//    }else{
//        NSArray *packCmdArr = @[@{
//            @"field":@"Pck_ctrlTimyear",
//            @"regAddr":@(6002),
//            @"bitWidth":@(16),
//            @"type":@"date",
//            @"cmdType":@(LocalSettingType_Pack1)
//        }];
//        
//        if ([CBLECenterMnger shareMnger].curPheral.wifiType == DevWiFiType362K) {
//            [cmdArr addObjectsFromArray:packCmdArr];
//        }
//    }
    
    
    NSArray *wifiCmdArr = @[@{
        @"field":@"STASSID:",
        @"type":@"text",
        @"cmdType":@(LocalSettingType_NetWorkConfig)
    },@{
        @"field":@"STAPWD:",
        @"type":@"text",
        @"cmdType":@(LocalSettingType_NetWorkConfig)
    },@{
        @"field":@"DEVKEY:",
        @"type":@"text",
        @"cmdType":@(LocalSettingType_NetWorkConfig)
    },@{
        @"field":@"COUNCODE:",
        @"type":@"text",
        @"cmdType":@(LocalSettingType_NetWorkConfig)
    },@{
        @"field":@"BRANDID:",
        @"type":@"text",
        @"cmdType":@(LocalSettingType_NetWorkConfig)
    },@{
        @"field":@"NET:",
        @"content":@"end",
        @"cmdType":@(LocalSettingType_NetWorkConfig)
    }];
    [cmdArr addObjectsFromArray:wifiCmdArr];
    
    NSMutableArray *mtbArr = [NSMutableArray array];
    [cmdArr enumerateObjectsUsingBlock:^(NSDictionary  *_Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
        RHLocalSettingModel *settingModel = [RHLocalSettingModel yy_modelWithJSON:dic];
        [mtbArr addObject:settingModel];
    }];
    self.cmdArray = mtbArr.copy;
}


-(void)checkDeviceId
{
    NSString *deviceId = [CBLECenterMnger shareMnger].curPheral.deviceId;
    NSString *deviceName = [CBLECenterMnger shareMnger].curPheral.devName;
    if(deviceId.length>0){
        [self getDeviceSecret:deviceId];
    }else if(deviceName.length>0){
        [self getDeviceSecret:deviceName];
    }
}

-(void)getDeviceSecret:(NSString *)deviceId
{
    //从后台获取设备秘钥
    [QMUITips showLoadingInView:self.view];
    [BaseModel startGetWithCompletionAPIKey:H_getDevicePassword argument:@{@"deviceId":ValidNullData(deviceId)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [QMUITips hideAllTips];
        if(resultModel.code == 200){
            NSString *pwd = ValidNullData(request.responseJSONObject[@"data"][@"password"]);
            self.secretTextField.text =  [NSString  base64Decode:pwd];
        }
        
                
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [QMUITips hideAllTips];
    }];
 
}
#pragma mark ----- 发送WIFI名称和密码 设备密钥  区域 品牌

-(void)sendSsidAndPassword
{
    if(_ssidInputV.text.length == 0){
        [QMUITips showError:@"请输入WiFi名称".rh_localized];
        return;
    }
    if (_passwordInputV.text.length == 0) {
        [QMUITips showError:@"请输入WiFi密码".rh_localized];
        return;
    }
    if (_secretTextField.text.length == 0) {
        [QMUITips showError:@"请输入设备密钥".rh_localized];
        return;
    }
    
    //校验密钥,不管是不是自己都检验,防止密钥不对的情况
    NSString *deviceId = [CBLECenterMnger shareMnger].curPheral.devName;//已去掉了K0 K1
    if (deviceId.length > 0) {
        [QMUITips showLoadingInView:self.view];
        [BaseModel startWithCompletionAPIKey:H_vetifyDevicePassword argument:@{@"deviceId":deviceId,@"password":self.secretTextField.text} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if (resultModel.code == 200) {
                [self sendComandToDevice];
                [self updateRemeberWiFiInfoStatus];
            }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
    }else{
        [QMUITips showInfo:@"设备id错误".rh_localized];
    }

}

-(void)sendComandToDevice
{
    
    //当前时区时间    (考虑设备旧固件指令没有回复或者master或者失联的情况,时间校准先去掉)
//    NSString *localDateString = [NSDate getCurrentTimeStringWithFormat:@"yyyy-MM-dd HH:mm:ss"];
//    //转成北京时间
//    NSString *beijinDateString = [NSDate localTimeConvertToBeiJinTime:localDateString];
//    
//    RHLocalSettingModel *dateModel    = self.cmdArray[0];//年月
//    dateModel.content = beijinDateString;
    
    RHLocalSettingModel *ssidModel   = self.cmdArray[0];//ssid
    ssidModel.content   = self.ssidInputV.text;
    RHLocalSettingModel *pwdModel    = self.cmdArray[1];//pwd
    pwdModel.content    = self.passwordInputV.text;
    RHLocalSettingModel *secretModel = self.cmdArray[2];//secret
    secretModel.content = self.secretTextField.text;
    RHLocalSettingModel *areaModel   = self.cmdArray[3];//area
    areaModel.content   = [kUserDefaults objectForKey:kRegionCode];
    RHLocalSettingModel *brandModel  = self.cmdArray[4];//brandId  当前登录的品牌
    brandModel.content  = [NSString stringWithFormat:@"%lld",[PrivateMange share].currentUser.topBrandId];
    
    [[RHBleCmdManager shareMnger] writeDeviceInfoFromBle:self.cmdArray];
}

-(void)updateRemeberWiFiInfoStatus
{
    //记住wifi名称和密码
    [kUserDefaults setBool:self.remeberBtn.selected forKey:kIsRememberWiFi];
    if (self.remeberBtn.selected) {
        [kUserDefaults setObject:self.ssidInputV.text forKey:kWiFiSSID];
        [kUserDefaults setObject:self.passwordInputV.text forKey:kWiFiPWD];
    }
}

-(void)receiveDeviceMsg:(NSNotification*)no
{
    NSDictionary *dic = [no object];
    if(dic.allKeys.count==0)return;
    if (!self.recieveMsg) return;
    NSLog(@"------>收到设备信息:%@",dic);
    
    if(!dic[CMD_ADDRESS])return;
    RHLocalSettingModel *endModel = [self.cmdArray lastObject];
   
    if([endModel.field hasPrefix:dic[CMD_ADDRESS]]){
        
        NSLog(@"---->%@ = %@",dic[CMD_ADDRESS],dic[CMD_ADDRESS_VALUE]);
      
        
        if([dic[CMD_ADDRESS_VALUE] isEqualToString:@"OK"]){
            
        
        }
        
        if([dic[CMD_ADDRESS_VALUE] isEqualToString:@"ERROR"]){
            //设置失败
            NSLog(@"写入失败:%@",endModel.field);
        }
    }

}

-(void)sendCmdFinish
{
    if(self.recieveMsg == NO){
        return;
    }
    [QMUITips showSucceed:@"设置成功".rh_localized inView:self.view hideAfterDelay:1.5];
    [CBLECenterMnger shareMnger].isManualDisconnect = YES;//设备会自动断开切到wifi模式,此时不上让重连
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.navigationController popToRootViewControllerAnimated:YES];
    });
}

- (void)setupUI{
    kWeakSelf;
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_ACK,receiveDeviceMsg:);
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_FINISH,sendCmdFinish);
    
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.backgroundColor = CFTabViewBgColor;
    [self.view addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    UIView *contentView = kView;
    contentView.backgroundColor = CFTabViewBgColor;
    [scrollView addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        make.width.offset(kUI_WINDOW_W);
    }];
    
    
    UIImageView *connectStateImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ble_connected"]];
    connectStateImg.contentMode = UIViewContentModeScaleAspectFit;
    [contentView addSubview:connectStateImg];
    [connectStateImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(30);
        make.width.mas_offset(kScaleW(225));
        make.height.mas_offset(kScaleW(113));
        make.centerX.mas_offset(0);
    }];
    
    UIImageView *connectedImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ble_connect_success"]];
    [contentView addSubview:connectedImage];
    [connectedImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.width.height.offset(25);
        make.top.equalTo(connectStateImg.mas_bottom).offset(30);
    }];
    
    QMUILabel *connectedLab = [QMUILabel labelWithText:@"APP已同设备建立通讯链接".rh_localized font:kSYSTEMFONT(15) textColor:kRGB(63, 68, 67)];
    connectedLab.numberOfLines = 0;
    [contentView addSubview:connectedLab];
    
    [connectedLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(connectedImage.mas_bottom).offset(15);
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
    }];
    
    
    QMUILabel *wifiTitle = [[QMUILabel alloc]init];
    wifiTitle.text = @"WiFi";
    wifiTitle.textColor = kRGB(63, 68, 67);
    wifiTitle.font = kSYSTEMFONT(16);
    [contentView addSubview:wifiTitle];
    [wifiTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.equalTo(connectedLab.mas_bottom).offset(30);
    }];
    
    UIView *wifiContentView = kView;
    wifiContentView.layer.cornerRadius = 8;
    wifiContentView.backgroundColor = UIColor.whiteColor;
    [contentView addSubview:wifiContentView];
    [wifiContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(wifiTitle);
        make.right.mas_offset(-15);
        make.top.equalTo(wifiTitle.mas_bottom).offset(5);
    }];
    
    
    QMUILabel *wifiNameLab = [[QMUILabel alloc]init];
    wifiNameLab.text = @"WiFi名称".rh_localized;
    wifiNameLab.textColor = kColorRGBA(63, 68, 67, 0.8);
    wifiNameLab.font = kSYSTEMFONT(14);
    [wifiContentView addSubview:wifiNameLab];
    [wifiNameLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.mas_offset(15);
    }];
    
    
    _ssidInputV = [[QMUITextField alloc] init];
    _ssidInputV.backgroundColor = kRGB(244, 244, 244);
    _ssidInputV.layer.cornerRadius = 8;
    _ssidInputV.placeholder =  @"请输入WiFi名称".rh_localized;
    _ssidInputV.textInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    _ssidInputV.text = [UserDefaults objectForKey:kWiFiSSID]?[UserDefaults objectForKey:kWiFiSSID]:[self getSSID];
    _ssidInputV.font = kSYSTEMFONT(14);
    [wifiContentView addSubview:_ssidInputV];
    
    UIView *ssidRightView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    QMUIButton *selectBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [selectBtn setImage:[UIImage imageNamed:@"arrow_2"] forState:UIControlStateNormal];
    [ssidRightView addSubview:selectBtn];
    _ssidInputV.rightView = ssidRightView;
    _ssidInputV.rightViewMode = UITextFieldViewModeAlways;
    [_ssidInputV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(wifiNameLab.mas_bottom).offset(15);
        make.height.mas_equalTo(45);
    }];

    
    
    
    QMUILabel *wifiPwdLab = [[QMUILabel alloc]init];
    wifiPwdLab.text = @"WiFi密码".rh_localized;
    wifiPwdLab.textColor = kColorRGBA(63, 68, 67, 0.8);
    wifiPwdLab.font = kSYSTEMFONT(14);
    [wifiContentView addSubview:wifiPwdLab];
    [wifiPwdLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.equalTo(weakSelf.ssidInputV.mas_bottom).offset(20);
    }];
    _passwordInputV = [[QMUITextField alloc] init];
    _passwordInputV.backgroundColor = kRGB(244, 244, 244);
    _passwordInputV.layer.cornerRadius = 8;
    _passwordInputV.placeholder = @"请输入WiFi密码".rh_localized;
    _passwordInputV.secureTextEntry = YES;
    _passwordInputV.textInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    _passwordInputV.text = [UserDefaults objectForKey:kWiFiPWD];
    _passwordInputV.font = kSYSTEMFONT(14);
    [wifiContentView addSubview:_passwordInputV];
    
    //是否记住wifi名称和密码
    if ([kUserDefaults boolForKey:kIsRememberWiFi]) {
        NSString *ssid = [kUserDefaults objectForKey:kWiFiSSID];
        NSString *pwd  = [kUserDefaults objectForKey:kWiFiPWD];
        self.ssidInputV.text = ssid;
        self.passwordInputV.text = pwd;
    }else{
        self.ssidInputV.text = [self getSSID];
    }
    
    UIView *pwdRightView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    QMUIButton *seeBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [pwdRightView addSubview:seeBtn];
    [seeBtn setImage:[UIImage imageNamed:@"kwt_show_pwd"] forState:UIControlStateNormal];
    [seeBtn setImage:[UIImage imageNamed:@"kwt_show_pwd_s"] forState:UIControlStateSelected];
    _passwordInputV.rightViewMode = UITextFieldViewModeAlways;
    _passwordInputV.rightView = pwdRightView;
    [_passwordInputV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(wifiPwdLab.mas_bottom).offset(15);
        make.height.mas_equalTo(45);
    }];
    
    QMUIButton *remeberBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [remeberBtn setTitle:@"记住名称和密码".rh_localized forState:UIControlStateNormal];
    [remeberBtn setTitleColor:kRGB(86, 194, 113) forState:UIControlStateNormal];
    [remeberBtn setImage:[UIImage imageNamed:@"remeber_normal"] forState:UIControlStateNormal];
    [remeberBtn setImage:[UIImage imageNamed:@"remeber_selected"] forState:UIControlStateSelected];
    remeberBtn.titleLabel.font = kSYSTEMFONT(12);
    remeberBtn.imagePosition = QMUIButtonImagePositionLeft;
    remeberBtn.spacingBetweenImageAndTitle = 10;
    [wifiContentView addSubview:remeberBtn];
    self.remeberBtn = remeberBtn;
    [remeberBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.passwordInputV.mas_bottom).offset(10);
        make.left.mas_offset(15);
        make.height.mas_offset(25);
        make.bottom.mas_offset(-15);
    }];
    remeberBtn.selected = [kUserDefaults boolForKey:kIsRememberWiFi];
    
    
    QMUILabel *scrTitleLab = [[QMUILabel alloc]init];
    scrTitleLab.text = @"设置密钥".rh_localized;
    scrTitleLab.textColor = kColorRGBA(63, 68, 67, 1);
    scrTitleLab.font = kSYSTEMFONT(16);
    [contentView addSubview:scrTitleLab];
    [scrTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.equalTo(wifiContentView.mas_bottom).offset(20);
    }];
    
    QMUIButton *helpBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [contentView addSubview:helpBtn];
    [helpBtn setImage:[UIImage imageNamed:@"secret_help"] forState:UIControlStateNormal];
    [helpBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(35);
        make.left.equalTo(scrTitleLab.mas_right).offset(0);
        make.centerY.equalTo(scrTitleLab);
    }];
    
    _secretTextField = [[QMUITextField alloc] init];
    _secretTextField.backgroundColor = UIColor.whiteColor;
    _secretTextField.layer.cornerRadius = 8;
    _secretTextField.placeholder = @"请输入设备密钥".rh_localized;
    _secretTextField.textInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    _secretTextField.font = kSYSTEMFONT(14);
    [contentView addSubview:_secretTextField];
    
    
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 35)];
    QMUIButton *scanBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [rightView addSubview:scanBtn];
    [scanBtn setImage:[UIImage imageNamed:@"input_scan_icon"] forState:UIControlStateNormal];
    _secretTextField.rightViewMode = UITextFieldViewModeAlways;
    _secretTextField.rightView = rightView;
    [_secretTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(scrTitleLab.mas_bottom).offset(15);
        make.height.mas_equalTo(45);
    }];
    
    
    QMUIButton *seeSecretBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [contentView addSubview:seeSecretBtn];
    [seeSecretBtn setTitle:@"查看设备密钥>>>".rh_localized forState:UIControlStateNormal];
    [seeSecretBtn setTitleColor:kColorRGBA(63, 68, 67, 0.8) forState:UIControlStateNormal];
    seeSecretBtn.titleLabel.font = kSYSTEMFONT(12);
    seeSecretBtn.hidden = YES;
    [seeSecretBtn mas_makeConstraints:^(MASConstraintMaker *make) {
      
        make.left.equalTo(weakSelf.secretTextField).offset(0);
        make.top.equalTo(weakSelf.secretTextField.mas_bottom).offset(10);
    }];
    
    QMUIButton *btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(0, 0, 204, 45)];
    [btn setBackgroundColor:UIColor.blackColor];
    [btn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [btn setTitle:@"确认".rh_localized forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [btn.layer setCornerRadius:8];
    [btn setBackgroundColor:CMainColorGreen];
    [contentView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(25);
        make.right.mas_offset(-25);
        make.top.equalTo(seeSecretBtn.mas_bottom).offset(30);
        make.height.mas_equalTo(50);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-20);
    }];


    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf sendSsidAndPassword];
    }];
    
    [[selectBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf.view endEditing:YES];
        [weakSelf getConfigWifiList];
        RHChoiceWiFiView *wifiView = [[RHChoiceWiFiView alloc]init];
        wifiView.curSsid = [weakSelf getSSID];
        wifiView.wifiList = @[[weakSelf getSSID]];
        if (wifiView.curSsid.length>0) {
            wifiView.wifiList = @[[weakSelf getSSID]];
        }
        
        wifiView.choiceResultBlock = ^(NSString * _Nonnull ssid) {
            weakSelf.ssidInputV.text = ssid;
        };
        [wifiView showAnimation];
    }];
    
    [[seeBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        x.selected = !x.selected;
        weakSelf.passwordInputV.secureTextEntry = !x.selected;
    }];
    
    [[remeberBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        x.selected = !x.selected;
    }];
    
    [[helpBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf showTipsViewWithContent:@"设备密钥是每台设备对应的入网凭证，在我的设备列表中-设备信息，可以找到设备密钥。设备密钥为机密信息，请妥善保存。".rh_localized];
    }];
    
    [[scanBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf scanQRC];
    }];
}





#pragma mark ------ 获取当前连接的WiFi名称
-(NSString *)getSSID
{
    NSString *ssid = @"";
    CFArrayRef arrRef = CNCopySupportedInterfaces();
    NSArray *ifs = (__bridge id)arrRef;
    for (NSString *ifnam in ifs) {
        CFDictionaryRef dicRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        NSDictionary *info = (__bridge id)dicRef;
        if (info[@"BSSID"]) {
            ssid = info[@"SSID"];
        }
        if(dicRef !=nil) {
            CFRelease(dicRef);
        }
    }
    if(arrRef != nil) {
        CFRelease(arrRef);
    }
    return ssid;
}

#pragma mark ------ 获取WiFi列表
//https://www.cnblogs.com/Free-Thinker/p/16135230.html
//需要申请开发 Network Extension 权限
- (void)getWifiList {


    dispatch_queue_t queue = dispatch_queue_create("com.leopardpan.HotspotHelper", 0);
    [NEHotspotHelper registerWithOptions:nil queue:queue handler: ^(NEHotspotHelperCommand * cmd) {
        if(cmd.commandType == kNEHotspotHelperCommandTypeFilterScanList) {
            for (NEHotspotNetwork* network  in cmd.networkList) {
                NSLog(@"network.SSID = %@",network.SSID);
            }
        }
    }];
}

#pragma mark ------ 获取已经连接过的WiFi列表
-(void)getConfigWifiList
{
//调用过这个方法后的才会有记录- (void)applyConfiguration:(NEHotspotConfiguration *)configuration
//completionHandler:(void (^ __nullable)(NSError * __nullable error))completionHandler
    [[NEHotspotConfigurationManager sharedManager] getConfiguredSSIDsWithCompletionHandler:^(NSArray<NSString *> * array) {
        for (NSString * str in array) {
            NSLog(@"加入过的WiFi：%@",str);

        }
    }];
}


-(void)showTipsViewWithContent:(NSString *)tips
{
    UIView *bgView = kView;
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    UIView *contentView = kView;
    contentView.backgroundColor = UIColor.whiteColor;
    contentView.layer.shadowColor = [UIColor grayColor].CGColor;
    contentView.layer.shadowRadius = 5;
    contentView.layer.shadowOpacity = 0.5;
    contentView.layer.cornerRadius = 8;
    contentView.layer.shadowOffset = CGSizeMake(0, 2);
    [bgView addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(25);
        make.right.mas_offset(-25);
        make.centerY.mas_offset(0);
    }];
    
    QMUILabel *tipsLab = [[QMUILabel alloc]init];
    tipsLab.textColor = kColorRGBA(63, 68, 67, 0.8);
    tipsLab.text = tips;
    tipsLab.font = kSYSTEMFONT(12);
    tipsLab.textAlignment = NSTextAlignmentCenter;
    tipsLab.numberOfLines = 0;
    tipsLab.qmui_lineHeight = 25;
    [contentView addSubview:tipsLab];
    [tipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.mas_offset(15);
    }];
    
    QMUIButton *sureBtn = [[QMUIButton alloc]init];
    [sureBtn setTitle:@"知道了".rh_localized forState:UIControlStateNormal];
    [sureBtn setTitleColor:kRGB(86, 194, 113) forState:UIControlStateNormal];
    sureBtn.titleLabel.font = kSYSTEMFONT(14);
    [contentView addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tipsLab.mas_bottom).offset(20);
        make.centerX.mas_offset(0);
        make.bottom.mas_offset(-15);
    }];
    
    
    kWeakSelf;
    [[sureBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [bgView removeFromSuperview];
    }];
}

//扫二维码
- (void)scanQRC{
    if ([self isCameraAvailable]) {
        [self isCanVisitPhotoAndCameraAuthorization:^(BOOL isOK,NSString *alerStr) {
            if (isOK) {
                NSLog(@"权限OK");
                kWeakSelf;
                CDZQRScanViewController *controller = [[CDZQRScanViewController alloc] init];
                controller.resultCallBack = ^(NSString *content) {
                    weakSelf.secretTextField.text = [NSString base64Decode:content] ;
                };
                 RHNavigationController *nav = [[RHNavigationController alloc] initWithRootViewController:controller];
                [nav setModalPresentationStyle:UIModalPresentationOverFullScreen];
                [self presentViewController:nav animated:YES completion:^{
                    
                }];
            }else{
                if (alerStr) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:alerStr preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"设置".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                         if (@available(iOS 10.0, *)) {
                             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                             } else {
                             NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                             if ([[UIApplication sharedApplication] canOpenURL:url]) {
                                 [[UIApplication sharedApplication] openURL:url];
                             }
                         }
                    }];
                    
                    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSLog(@"点击了取消按钮");
                    }];
                    [alert addAction:cancel];
                    [alert addAction:conform];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }
        }];
    }

}

// 判断设备是否有摄像头
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
- (void)isCanVisitPhotoAndCameraAuthorization:(void(^)(BOOL isOK,NSString *alerStr))result {
    PHAuthorizationStatus photo_status = [PHPhotoLibrary authorizationStatus];
    AVAuthorizationStatus camera_status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (photo_status == PHAuthorizationStatusAuthorized&&camera_status ==AVAuthorizationStatusAuthorized) {
        result(YES,nil);
        return;
    }
    
    if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied||
        camera_status ==AVAuthorizationStatusDenied || camera_status ==AVAuthorizationStatusRestricted) {
        if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied) {
            result(NO,@"请在系统设置中打开相册使用权限");
        }else{
            result(NO,@"请在系统设置中打开摄像头使用权限");
        }
        return ;
    }
    
    if (camera_status == AVAuthorizationStatusNotDetermined) {
        //点击弹框授权
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(!granted){//不允许
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"未开启相机权限,请到设置中开启");
                    result(NO,nil);
                });
            }else{
                if (photo_status == PHAuthorizationStatusNotDetermined) {
                    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                               // 回调是在子线程的
                               NSLog(@"%@",[NSThread currentThread]);
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (status != PHAuthorizationStatusAuthorized) {
                                         NSLog(@"未开启相册权限,请到设置中开启");
                                         result(NO,nil);
                                   }else{
                                         result(YES,nil);
                                   }
                               });
                     
                           }];
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        result(YES,nil);
                    });
                }

            }
        }];
        return;
    }
    
    if (photo_status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                   // 回调是在子线程的
                   NSLog(@"%@",[NSThread currentThread]);
                   dispatch_async(dispatch_get_main_queue(), ^{
                       if (status != PHAuthorizationStatusAuthorized) {
                             NSLog(@"未开启相册权限,请到设置中开启");
                             result(NO,nil);
                       }else{
                             result(YES,nil);
                       }
                   });
               }];
    }
}





-(void)dealloc
{
    [[CBLECenterMnger shareMnger] cmdDisconnectCurPheral];
}

@end
